#!/usr/bin/python
# -*- coding: utf8 -*-
import os,sys
import glob 
import re
import fnmatch
#from magnetools import choosewithnumber
"""option"""
debug=0
"""END:options"""

settings="HOME"
if os.sys.platform.startswith("win"): settings="USERPROFILE"
settings_dir=os.path.join(os.getenv(settings),".purple")
# May use : os.path.join(os.path.expanduser("~"), "Python")
if os.path.exists(settings_dir) == False:
    print "Pidgin settings dir doesn't existst (" + settings_dir + ")"
    sys.exit(1)

def chosedirwithnumber(startdir, message):
    """Function which permit the user to chose one subdirectory form all
    the subdirectory of the start directory given in parameter."""
    output={}
    i=0
    for dir in os.listdir(startdir):
        i=i+1
        print "%i \t %s" % (i, dir)
        output[i]=dir
    while 1:
        result=raw_input(message)
        if (result== "q"):
            return
        try:
            resultint=int(result)
        except:
            print "Enter a number or q for quit"
            continue
        if ((resultint > i) or (resultint < 0)):
            print "Non valid"
        else:
            return output[resultint]
"""STATS FUNCTION"""
def calculatestats(address,sentence,nick=None):
    global lastspeak
    if debug: print "--- This sentence belong to : " + address
    """Count lines"""
    stats[address]["lines"]=stats[testadress]["lines"]+1
    """Count words"""
    stats[address]["words"]=stats[testadress]["words"]+len(sentence.split(' '))
    """Same count with ignoring small lines (<3 words)"""
    if (len(sentence.split(' ')) > 3): 
        stats[address]["lineswshort"]=stats[address]["lineswshort"]+1
        stats[address]["wordswshort"]=stats[address]["wordswshort"]+len(sentence.split(' '))
    """To count multiple lines, set a variable with the
    last person who speak"""
    lastspeak=testadress
    """Setting up list of aliases"""
    if nick:
        if (not nick in stats[address]["aliases"]):
            stats[address]["aliases"].append(nick)
if (len(sys.argv) == 1):
    #TODO: tests between eatch        
    protocol=chosedirwithnumber(os.path.join(settings_dir,"logs"), "Chose the protocol you want (q for quit):")
    adress=chosedirwithnumber(os.path.join(settings_dir,"logs",protocol), "Chose the adress you want (q for quit):")
    contact=chosedirwithnumber(os.path.join(settings_dir,"logs",protocol,adress), "Chose the contact you want (q for quit):")
elif (len(sys.argv) == 4):
    protocol=sys.argv[1]
    adress=sys.argv[2]
    contact=sys.argv[3]
else:
    print "Usage: stats.py protocol adress contact"
    sys.exit(1)
"""Okay, now we have the good directory, time to stats !"""

"""Define variables"""
index=0
addresses=[]
stats={}
popularization=0
lastspeak=None
print "Analysing file..."
for files in glob.glob(os.path.join(settings_dir,"logs",protocol,adress,contact,"*")):
    """Todo for each files"""
    file=open(files, 'r')
    lignes=file.readlines()
    for lignetemp in lignes:
        ligne=lignetemp.strip("\n")
        """Determination if the ligne is a conversation"""
        isconversation=re.search(r"^Conversation with (.+) at .* on (.+) \(.+\)$", ligne)
        if isconversation and not popularization:
            for address in isconversation.groups():
                temp=raw_input("Pattern nickname (use *) for the contact : " + address +"\n")
                """Popularize addresses with all the contacts adresses
                then checkt the dictionnary stats to put the pattern"""
                addresses.append(address)
                stats[address]={"pattern":temp, "lines":0, "words":0, "lineswshort":0, "wordswshort":0, "aliases":[]}
            popularization=1
        else:
            conversation=re.search(r"^\(([0-9]{2}:?){3}\) (.+): (.*)$", ligne)
            if conversation:
                if (len(conversation.groups()) > 3):
                    print "Unknown error..."
                    sys.exit(1)
                nick=conversation.group(2)
                sentence=conversation.group(3)
                """Trying to identify who is it"""
                for testadress in addresses:
                    if fnmatch.fnmatch(nick,stats[testadress]["pattern"]):
                        calculatestats(testadress,sentence,nick)
            else:
                systemessage=re.search(r"(Le message peut ne pas avoir été envoyé à cause)|(Impossible d'envoyer le message à cause)|(n'est plus inactif.)|(est devenu inactif.)|(Conversation with)|(Démarrage du transfert)|(est désormais connu sous le nom de)|(vient de se (dé)?connecter\.)|(a annulé le transfert de)|(propose de vous envoyer)|(Transfert du fichier)|(est passé absent.)|(n'est plus absent.)",ligne)
                if not systemessage:
                    if lastspeak:
                        calculatestats(testadress,ligne)
"""Calculating some stuffs"""
totallines=stats[addresses[0]]["lines"]+stats[addresses[1]]["lines"]
totalwords=stats[addresses[0]]["words"]+stats[addresses[1]]["words"]
totallineswshort=stats[addresses[0]]["lineswshort"]+stats[addresses[1]]["lineswshort"]
totalwordswshort=stats[addresses[0]]["wordswshort"]+stats[addresses[1]]["wordswshort"]
totalnicks=len(stats[addresses[0]]["aliases"])+len(stats[addresses[1]]["aliases"])
"""Displaying stats"""
print "Stats \t \t \t" + addresses[0] + "\t\t" + addresses[1] + "\t" + "Total"
print "Number of lines : \t %i \t (%i%%) \t\t\t %i \t (%i%%) \t\t %i\t(100%%)" % (stats[addresses[0]]["lines"],stats[addresses[0]]["lines"]*100/totallines,stats[addresses[1]]["lines"],stats[addresses[1]]["lines"]*100/totallines,totallines)
print "Number of words : \t %i \t (%i%%) \t\t\t %i \t (%i%%) \t\t %i\t(100%%)" % (stats[addresses[0]]["words"],stats[addresses[0]]["words"]*100/totalwords,stats[addresses[1]]["words"],stats[addresses[1]]["words"]*100/totalwords,totalwords)
print "Without small lines"
print "Number of lines : \t %i \t (%i%%) \t\t\t %i \t (%i%%) \t\t %i\t(100%%)" % (stats[addresses[0]]["lineswshort"],stats[addresses[0]]["lineswshort"]*100/totallineswshort,stats[addresses[1]]["lineswshort"],stats[addresses[1]]["lineswshort"]*100/totallineswshort,totallineswshort)
print "Number of words : \t %i \t (%i%%) \t\t\t %i \t (%i%%) \t\t %i\t(100%%)" % (stats[addresses[0]]["wordswshort"],stats[addresses[0]]["wordswshort"]*100/totalwordswshort,stats[addresses[1]]["wordswshort"],stats[addresses[1]]["wordswshort"]*100/totalwordswshort,totalwordswshort)
print "-----------------"
print "Number of nicknames \t %i \t (%i%%) \t\t\t %i \t (%i%%) \t\t %i\t(100%%)" % (len(stats[addresses[0]]["aliases"]),len(stats[addresses[0]]["aliases"])*100/totalnicks,len(stats[addresses[1]]["aliases"]),len(stats[addresses[1]]["aliases"])*100/totalnicks,totalnicks)